<template>
  <div class="news-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Document /></el-icon>
            <span class="header-title">新闻管理</span>
          </div>
          <el-button type="primary" @click="openDialog" :icon="Plus">
            新增新闻
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标题、分类或内容"
          clearable
          style="max-width: 300px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="filterCategory"
          placeholder="选择分类"
          clearable
          style="width: 150px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="信息" value="信息" />
          <el-option label="活动" value="活动" />
          <el-option label="救助" value="救助" />
          <el-option label="招募" value="招募" />
          <el-option label="科技" value="科技" />
          <el-option label="倡议" value="倡议" />
        </el-select>
        <el-select
          v-model="filterStatus"
          placeholder="选择状态"
          clearable
          style="width: 120px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="已发布" :value="1" />
          <el-option label="草稿" :value="0" />
        </el-select>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.categoryName)" size="small">
              {{ row.categoryName || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者" width="120" align="center" />
        <el-table-column prop="source" label="来源" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
              {{ row.status === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="置顶" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isTop === 1" type="danger" size="small">置顶</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="views" label="浏览量" width="100" align="center" />
        <el-table-column prop="likes" label="点赞数" width="100" align="center" />
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="primary" 
              @click="edit(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty v-if="!loading && filteredList.length === 0" description="暂无新闻" :image-size="150" />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑新闻' : '新增新闻'"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="form" 
        :rules="formRules"
        ref="formRef"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input 
                v-model="form.title" 
                placeholder="请输入新闻标题"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="副标题" prop="subtitle">
              <el-input 
                v-model="form.subtitle" 
                placeholder="请输入副标题"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryName">
              <el-select v-model="form.categoryName" placeholder="请选择分类" style="width: 100%;">
                <el-option label="信息" value="信息" />
                <el-option label="活动" value="活动" />
                <el-option label="救助" value="救助" />
                <el-option label="招募" value="招募" />
                <el-option label="科技" value="科技" />
                <el-option label="倡议" value="倡议" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input 
                v-model="form.author" 
                placeholder="请输入作者"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="来源" prop="source">
              <el-select v-model="form.source" placeholder="请选择来源" style="width: 100%;">
                <el-option label="原创" value="原创" />
                <el-option label="转载" value="转载" />
                <el-option label="编译" value="编译" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="封面图" prop="coverImage">
              <el-upload
                :action="uploadAction"
                :headers="uploadHeaders"
                :on-success="handleCoverImageSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                list-type="picture-card"
                :limit="1"
                :file-list="coverImageList"
                :on-remove="handleRemoveCover"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="图片列表" prop="images">
              <el-upload
                :http-request="handleImagesUpload"
                :on-success="handleImagesSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                :multiple="true"
                list-type="picture-card"
                :limit="9"
                :file-list="imagesList"
                :on-remove="handleRemoveImage"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">支持上传多张图片，最多9张</div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                <el-option label="草稿" :value="0" />
                <el-option label="已发布" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="置顶">
              <el-switch 
                v-model="form.isTop" 
                :active-value="1" 
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="标签" prop="tags">
              <el-input 
                v-model="form.tags" 
                placeholder="请输入标签，多个标签用逗号分隔"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <el-input 
                v-model="form.content" 
                type="textarea" 
                placeholder="请输入新闻内容"
                :rows="10"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Document, Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue';

export default {
  name: 'News',
  components: {
    Document,
    Plus,
    Search,
    Refresh,
    Edit,
    Delete
  },
  data() {
    return {
      loading: false,
      saving: false,
      list: [],
      searchKeyword: '',
      filterCategory: '',
      filterStatus: '',
      dialogVisible: false,
      isEdit: false,
      uploadAction: 'http://localhost:8080/api/news/uploadCover',
      uploadImagesAction: 'http://localhost:8080/api/news/upload',
      uploadHeaders: {},
      coverImageList: [],
      imagesList: [],
      form: {
        title: '',
        subtitle: '',
        categoryName: '',
        author: '',
        source: '原创',
        coverImage: '',
        images: '',
        content: '',
        status: 1,
        isTop: 0,
        tags: ''
      },
      formRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        categoryName: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    filteredList() {
      let result = this.list;
      
      // 关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(item => 
          (item.title || '').toLowerCase().includes(keyword) ||
          (item.categoryName || '').toLowerCase().includes(keyword) ||
          (item.content || '').toLowerCase().includes(keyword)
        );
      }
      
      // 分类筛选
      if (this.filterCategory) {
        result = result.filter(item => item.categoryName === this.filterCategory);
      }
      
      // 状态筛选
      if (this.filterStatus !== '') {
        result = result.filter(item => item.status === this.filterStatus);
      }
      
      return result;
    }
  },
  async mounted() {
    await this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const res = await axios.get('http://localhost:8080/api/news/list', {
          params: {
            page: 1,
            size: 100
          }
        });
        if (res.data && res.data.records) {
          this.list = res.data.records;
        } else if (Array.isArray(res.data)) {
          this.list = res.data;
        }
      } catch (error) {
        console.error('加载新闻列表失败:', error);
        ElMessage.error('加载新闻列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    openDialog() {
      this.isEdit = false;
      this.form = {
        title: '',
        subtitle: '',
        categoryName: '',
        author: '',
        source: '原创',
        coverImage: '',
        images: '',
        content: '',
        status: 1,
        isTop: 0,
        tags: ''
      };
      this.coverImageList = [];
      this.imagesList = [];
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate();
        }
      });
    },
    
    edit(row) {
      this.isEdit = true;
      this.form = {
        id: row.id,
        title: row.title || '',
        subtitle: row.subtitle || '',
        categoryName: row.categoryName || '',
        author: row.author || '',
        source: row.source || '原创',
        coverImage: row.coverImage || '',
        images: row.images || '',
        content: row.content || '',
        status: row.status !== undefined ? row.status : 1,
        isTop: row.isTop !== undefined ? row.isTop : 0,
        tags: row.tags || ''
      };
      
      // 设置封面图列表
      if (this.form.coverImage) {
        this.coverImageList = [{
          name: 'cover',
          url: this.form.coverImage
        }];
      } else {
        this.coverImageList = [];
      }
      
      // 设置图片列表
      if (this.form.images) {
        const imageUrls = this.form.images.split(',').filter(url => url.trim());
        this.imagesList = imageUrls.map((url, index) => ({
          name: `image_${index}`,
          url: url.trim()
        }));
      } else {
        this.imagesList = [];
      }
      
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate();
        }
      });
    },
    
    async handleSave() {
      if (!this.$refs.formRef) return;
      
      try {
        await this.$refs.formRef.validate();
        this.saving = true;
        
        const payload = { ...this.form };
        
        if (this.form.id) {
          // 更新
          await axios.put(`http://localhost:8080/api/news/update/${this.form.id}`, payload);
          ElMessage.success('更新成功');
        } else {
          // 新增
          delete payload.id;
          await axios.post('http://localhost:8080/api/news/add', payload);
          ElMessage.success('新增成功');
        }
        
        this.dialogVisible = false;
        await this.loadData();
      } catch (error) {
        if (error.errors) {
          // 表单验证错误
          return;
        }
        console.error('保存失败:', error);
        ElMessage.error(error.response?.data?.msg || '保存失败');
      } finally {
        this.saving = false;
      }
    },
    
    async handleDelete(id) {
      try {
        await ElMessageBox.confirm(
          '确定要删除这条新闻吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        await axios.delete(`http://localhost:8080/api/news/delete/${id}`);
        ElMessage.success('删除成功');
        await this.loadData();
      } catch (error) {
        if (error === 'cancel') return;
        console.error('删除失败:', error);
        ElMessage.error(error.response?.data?.msg || '删除失败');
      }
    },
    
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    
    handleReset() {
      this.searchKeyword = '';
      this.filterCategory = '';
      this.filterStatus = '';
    },
    
    formatTime(time) {
      if (!time) return '-';
      try {
        const date = new Date(time.replace(' ', 'T'));
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return time;
      }
    },
    
    getCategoryType(category) {
      const types = {
        '活动': 'success',
        '救助': 'warning',
        '招募': 'primary',
        '科技': 'info',
        '倡议': 'danger',
        '信息': 'primary'
      };
      return types[category] || 'primary';
    },
    
    // 上传相关方法
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        return false;
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    
    handleCoverImageSuccess(response, file) {
      // 处理封面图上传（使用 /uploadCover 接口）
      if (response.code === 200 && response.url) {
        this.form.coverImage = response.url;
        this.coverImageList = [{
          name: file.name,
          url: response.url
        }];
        ElMessage.success('封面上传成功');
      } else if (response.data && response.data.code === 200 && response.data.url) {
        // 如果响应被包裹在 data 中
        this.form.coverImage = response.data.url;
        this.coverImageList = [{
          name: file.name,
          url: response.data.url
        }];
        ElMessage.success('封面上传成功');
      } else {
        ElMessage.error(response.msg || response.data?.msg || '上传失败：无法获取图片URL');
      }
    },
    
    // 自定义多图片上传
    async handleImagesUpload(options) {
      const formData = new FormData();
      formData.append('files', options.file);
      formData.append('type', 'news');

      try {
        const res = await axios.post(this.uploadImagesAction, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (res.data.code === 200) {
          const response = res.data;
          // 处理返回的URLs
          if (response.urls && Array.isArray(response.urls)) {
            // 合并新的图片URL到现有列表
            const existingUrls = this.form.images ? this.form.images.split(',').filter(url => url.trim()) : [];
            const newUrls = response.urls.filter(url => !existingUrls.includes(url));
            const allUrls = [...existingUrls, ...newUrls];
            this.form.images = allUrls.join(',');
            
            // 更新图片列表显示
            this.imagesList = allUrls.map((url, index) => ({
              name: `image_${index}`,
              url: url.trim()
            }));
            
            ElMessage.success(`成功上传 ${response.urls.length} 张图片`);
          } else if (response.joinedUrls) {
            // 如果返回的是逗号分隔的字符串
            this.form.images = response.joinedUrls;
            const urls = response.joinedUrls.split(',').filter(url => url.trim());
            this.imagesList = urls.map((url, index) => ({
              name: `image_${index}`,
              url: url.trim()
            }));
            ElMessage.success('上传成功');
          }
          
          // 调用 onSuccess 回调
          if (options.onSuccess) {
            options.onSuccess(response, options.file);
          }
        } else {
          ElMessage.error(response.msg || '上传失败');
          if (options.onError) {
            options.onError(new Error(response.msg || '上传失败'));
          }
        }
      } catch (error) {
        console.error('上传失败:', error);
        ElMessage.error('上传失败：' + (error.response?.data?.msg || error.message));
        if (options.onError) {
          options.onError(error);
        }
      }
    },
    
    handleImagesSuccess(response, file, fileList) {
      // 这个方法现在主要用于更新 fileList，实际处理已在 handleImagesUpload 中完成
      this.imagesList = fileList;
    },
    
    handleUploadError() {
      ElMessage.error('图片上传失败');
    },
    
    handleRemoveCover() {
      this.form.coverImage = '';
      this.coverImageList = [];
    },
    
    handleRemoveImage(file, fileList) {
      // 从 form.images 中移除对应的 URL
      const urls = this.form.images ? this.form.images.split(',').filter(url => url.trim()) : [];
      const filteredUrls = urls.filter(url => url !== file.url);
      this.form.images = filteredUrls.join(',');
      this.imagesList = fileList;
    }
  }
};
</script>

<style scoped>
.news-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table__header th) {
  background: #fafafa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table__row:hover) {
  background: #f5f7fa;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.el-upload--picture-card .el-icon) {
  font-size: 28px;
  color: #8c939d;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

/* 响应式 */
@media (max-width: 768px) {
  .news-page {
    padding: 15px;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input,
  .search-bar .el-select {
    max-width: 100% !important;
    width: 100% !important;
  }
}
</style>
